package com.demo.base.auth.weixin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description 获取微信小程序openId
 * @date 2023/3/14 2:38 PM
 */
@Component
@Slf4j
public class WeCode2Session {

    /** 注入微信小程序配置config */
    private WeConfig weConfig;

    @Autowired
    public void setWeConfig(WeConfig weConfig) {
        this.weConfig = weConfig;
    }

    /**
     * 根据code获取openId
     *
     * @param code
     * @return
     */
    public String getOpenIdByCode(String code) {

        try {
            // 拼接请求url
            String url =
                    weConfig.getUrl()
                            + weConfig.getAppidPrefix()
                            + weConfig.getAppId()
                            + weConfig.getSecretPrefix()
                            + weConfig.getSecret()
                            + weConfig.getJsCodePrefix()
                            + code
                            + weConfig.getSuffix();

            // 初始化请求客户端
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            // DefaultHttpClient();
            // GET方式
            HttpGet httpget = new HttpGet(url);
            CloseableHttpResponse response;

            // 配置信息
            RequestConfig requestConfig =
                    RequestConfig.custom()
                            // 设置连接超时时间(单位毫秒)
                            .setConnectTimeout(5000)
                            // 设置请求超时时间(单位毫秒)
                            .setConnectionRequestTimeout(5000)
                            // socket读写超时时间(单位毫秒)
                            .setSocketTimeout(5000)
                            // 设置是否允许重定向(默认为true)
                            .setRedirectsEnabled(false)
                            .build();

            // 将上面的配置信息 运用到这个Get请求里
            httpget.setConfig(requestConfig);

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpget);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            log.info("获取微信openId响应状态为：{}", response.getStatusLine());

            // 获取响应内容
            if (responseEntity == null) {
                log.error("获取微信小程序openId失败");

                return null;
            }

            // 记录返回结果
            String res = EntityUtils.toString(responseEntity);
            log.info("获取微信openId响应内容为：{}", res);

            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }

            // 获取openId
            JSONObject jo = JSON.parseObject(res);
            String openid = jo.getString("openid");
            log.info("微信小程序登录，openid：{}", openid);

            // 获取openId失败，抛出异常
            if (StringUtils.isBlank(openid)) {
                log.error("获取微信小程序openId失败，openId为空");

                return null;
            }

            // 返回openId
            return openid;

        } catch (Exception ex) {
            log.error("获取微信小程序openId失败，原因：{}", ex.getMessage());

            return null;
        }
    }
}
